<template>
	<div class="page-container">
		<h1>温度单位转换</h1>
		<el-form>
			<el-form-item label="摄氏度">
				<el-input v-model.number="valC" placeholder="请输入摄氏度" @input="convert($event,'C')"></el-input>
			</el-form-item>

			<el-form-item label="华氏度">
				<el-input v-model.number="valF" placeholder="请输入华氏度" @input="convert($event,'F')"></el-input>
			</el-form-item>

			<el-form-item label="开氏度">
				<el-input v-model.number="valK" placeholder="请输入开氏度" @input="convert($event,'K')"></el-input>
			</el-form-item>

			<el-form-item label="兰氏度">
				<el-input v-model.number="valRa" placeholder="请输入兰氏度" @input="convert($event,'Ra')"></el-input>
			</el-form-item>

			<el-form-item label="列氏度">
				<el-input v-model.number="valRe" placeholder="请输入列氏度" @input="convert($event,'Re')"></el-input>
			</el-form-item>
			
			<el-form-item style="text-align: right;">
				<el-button @click="clear()">重置</el-button>
				<el-button @click="$router.back()">返回</el-button>
			</el-form-item>
		</el-form>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				valC: "",
				valF: "",
				valK: "",
				valRa: "",
				valRe: "",
			};
		},
		methods: {
			convert(number, type) {
				if (number.length < 1) {
					this.clear();
					return;
				}
				let cels = 0;
				number = Number(number);
				switch (type) {
					case "C":
						cels = number;
						break;
					case "F":
						cels = (number - 32) / 1.8;
						break;
					case "K":
						cels = number - 273.15;
						break;
					case "Ra":
						cels = (number - 32 - 459.67) / 1.8;
						break;
					case "Re":
						cels = number * 1.25;
						break;
				}

				const toFixed = (i, val) =>
					type === i ? number : parseFloat(val.toFixed(2));

				cels = Number(cels);
				this.valC = toFixed("C", cels);
				this.valF = toFixed("F", cels * 1.8 + 32);
				this.valK = toFixed("K", cels + 273.15);
				this.valRa = toFixed("Ra", cels * 1.8 + 32 + 459.67);
				this.valRe = toFixed("Re", cels * 0.8);
			},

			clear() {
				this.valC = "";
				this.valF = "";
				this.valK = "";
				this.valRa = "";
				this.valRe = "";
			},
		},
	};
</script>
